# 创建系统配置管理页面
<template>
  <div class="monitor-config">
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 系统参数配置 -->
      <el-tab-pane label="系统参数" name="system">
        <el-form
          ref="systemFormRef"
          :model="systemConfig"
          :rules="systemRules"
          label-width="120px"
          class="config-form"
        >
          <el-form-item label="系统名称" prop="systemName">
            <el-input v-model="systemConfig.systemName" />
          </el-form-item>
          
          <el-form-item label="系统描述" prop="description">
            <el-input
              v-model="systemConfig.description"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          
          <el-form-item label="数据保留时间" prop="dataRetentionDays">
            <el-input-number
              v-model="systemConfig.dataRetentionDays"
              :min="1"
              :max="365"
            />
            <span class="unit">天</span>
          </el-form-item>
          
          <el-form-item label="数据采集间隔" prop="collectionInterval">
            <el-input-number
              v-model="systemConfig.collectionInterval"
              :min="10"
              :max="3600"
              :step="10"
            />
            <span class="unit">秒</span>
          </el-form-item>
          
          <el-form-item label="系统时区" prop="timezone">
            <el-select v-model="systemConfig.timezone">
              <el-option label="UTC+8 (北京时间)" value="Asia/Shanghai" />
              <el-option label="UTC+0 (格林威治时间)" value="UTC" />
              <el-option label="UTC-8 (太平洋时间)" value="America/Los_Angeles" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="系统状态" prop="status">
            <el-switch
              v-model="systemConfig.status"
              active-text="启用"
              inactive-text="停用"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSaveSystemConfig">保存配置</el-button>
            <el-button @click="handleResetSystemConfig">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 监控规则配置 -->
      <el-tab-pane label="监控规则" name="monitor">
        <div class="rule-header">
          <el-button type="primary" @click="handleAddMonitorRule">
            添加规则
          </el-button>
        </div>
        
        <el-table :data="monitorRules" border style="width: 100%">
          <el-table-column type="index" width="50" />
          <el-table-column prop="name" label="规则名称" min-width="150" />
          <el-table-column prop="type" label="监控类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getMonitorTypeTag(row.type)">
                {{ getMonitorTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="target" label="监控目标" min-width="150" />
          <el-table-column prop="interval" label="检查间隔" width="100">
            <template #default="{ row }">
              {{ row.interval }}秒
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleMonitorRuleStatusChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditMonitorRule(row)">
                编辑
              </el-button>
              <el-button type="primary" link @click="handleTestMonitorRule(row)">
                测试
              </el-button>
              <el-button type="danger" link @click="handleDeleteMonitorRule(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 监控规则表单对话框 -->
        <el-dialog
          v-model="monitorRuleDialogVisible"
          :title="monitorRuleForm.id ? '编辑监控规则' : '添加监控规则'"
          width="600px"
        >
          <el-form
            ref="monitorRuleFormRef"
            :model="monitorRuleForm"
            :rules="monitorRuleRules"
            label-width="120px"
          >
            <el-form-item label="规则名称" prop="name">
              <el-input v-model="monitorRuleForm.name" />
            </el-form-item>
            
            <el-form-item label="监控类型" prop="type">
              <el-select v-model="monitorRuleForm.type">
                <el-option label="系统资源" value="resource" />
                <el-option label="性能指标" value="performance" />
                <el-option label="业务指标" value="business" />
                <el-option label="安全指标" value="security" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="监控目标" prop="target">
              <el-input v-model="monitorRuleForm.target" />
            </el-form-item>
            
            <el-form-item label="检查间隔" prop="interval">
              <el-input-number
                v-model="monitorRuleForm.interval"
                :min="10"
                :max="3600"
                :step="10"
              />
              <span class="unit">秒</span>
            </el-form-item>
            
            <el-form-item label="阈值设置" prop="thresholds">
              <el-table :data="monitorRuleForm.thresholds" border>
                <el-table-column label="级别" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getAlertLevelTag(row.level)">
                      {{ row.level }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="条件" width="120">
                  <template #default="{ row }">
                    <el-select v-model="row.operator">
                      <el-option label="大于" value=">" />
                      <el-option label="小于" value="<" />
                      <el-option label="等于" value="=" />
                      <el-option label="不等于" value="!=" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="阈值">
                  <template #default="{ row }">
                    <el-input-number v-model="row.value" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="80">
                  <template #default="{ $index }">
                    <el-button
                      type="danger"
                      link
                      @click="handleRemoveThreshold($index)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="threshold-actions">
                <el-button type="primary" link @click="handleAddThreshold">
                  添加阈值
                </el-button>
              </div>
            </el-form-item>
            
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="monitorRuleForm.status"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="monitorRuleDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveMonitorRule">
                保存
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>

      <!-- 告警规则配置 -->
      <el-tab-pane label="告警规则" name="alert">
        <div class="rule-header">
          <el-button type="primary" @click="handleAddAlertRule">
            添加规则
          </el-button>
        </div>
        
        <el-table :data="alertRules" border style="width: 100%">
          <el-table-column type="index" width="50" />
          <el-table-column prop="name" label="规则名称" min-width="150" />
          <el-table-column prop="type" label="告警类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getAlertTypeTag(row.type)">
                {{ getAlertTypeLabel(row.type) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="level" label="告警级别" width="100">
            <template #default="{ row }">
              <el-tag :type="getAlertLevelTag(row.level)">
                {{ row.level }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="channels" label="通知渠道" min-width="150">
            <template #default="{ row }">
              <el-tag
                v-for="channel in row.channels"
                :key="channel"
                class="channel-tag"
              >
                {{ getChannelLabel(channel) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-switch
                v-model="row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleAlertRuleStatusChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEditAlertRule(row)">
                编辑
              </el-button>
              <el-button type="primary" link @click="handleTestAlertRule(row)">
                测试
              </el-button>
              <el-button type="danger" link @click="handleDeleteAlertRule(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 告警规则表单对话框 -->
        <el-dialog
          v-model="alertRuleDialogVisible"
          :title="alertRuleForm.id ? '编辑告警规则' : '添加告警规则'"
          width="600px"
        >
          <el-form
            ref="alertRuleFormRef"
            :model="alertRuleForm"
            :rules="alertRuleRules"
            label-width="120px"
          >
            <el-form-item label="规则名称" prop="name">
              <el-input v-model="alertRuleForm.name" />
            </el-form-item>
            
            <el-form-item label="告警类型" prop="type">
              <el-select v-model="alertRuleForm.type">
                <el-option label="系统告警" value="system" />
                <el-option label="业务告警" value="business" />
                <el-option label="性能告警" value="performance" />
                <el-option label="安全告警" value="security" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="告警级别" prop="level">
              <el-select v-model="alertRuleForm.level">
                <el-option label="严重" value="严重" />
                <el-option label="高" value="高" />
                <el-option label="中" value="中" />
                <el-option label="低" value="低" />
              </el-select>
            </el-form-item>
            
            <el-form-item label="通知渠道" prop="channels">
              <el-checkbox-group v-model="alertRuleForm.channels">
                <el-checkbox label="email">邮件</el-checkbox>
                <el-checkbox label="sms">短信</el-checkbox>
                <el-checkbox label="webhook">Webhook</el-checkbox>
                <el-checkbox label="dingtalk">钉钉</el-checkbox>
                <el-checkbox label="wechat">企业微信</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            
            <el-form-item label="通知模板" prop="template">
              <el-input
                v-model="alertRuleForm.template"
                type="textarea"
                :rows="4"
                placeholder="支持变量：${alertName}、${alertLevel}、${alertTime}、${alertContent}"
              />
            </el-form-item>
            
            <el-form-item label="静默期" prop="silencePeriod">
              <el-input-number
                v-model="alertRuleForm.silencePeriod"
                :min="0"
                :max="1440"
                :step="5"
              />
              <span class="unit">分钟</span>
            </el-form-item>
            
            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="alertRuleForm.status"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="alertRuleDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSaveAlertRule">
                保存
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getSystemConfig,
  updateSystemConfig,
  getMonitorRules,
  createMonitorRule,
  updateMonitorRule,
  deleteMonitorRule,
  testMonitorRule,
  getAlertRules,
  createAlertRule,
  updateAlertRule,
  deleteAlertRule,
  testAlertRule
} from '@/api/message'

// 当前激活的标签页
const activeTab = ref('system')

// 系统配置表单
const systemFormRef = ref(null)
const systemConfig = reactive({
  systemName: '',
  description: '',
  dataRetentionDays: 30,
  collectionInterval: 60,
  timezone: 'Asia/Shanghai',
  status: true
})

// 系统配置表单验证规则
const systemRules = {
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '不能超过 200 个字符', trigger: 'blur' }
  ],
  dataRetentionDays: [
    { required: true, message: '请设置数据保留时间', trigger: 'blur' }
  ],
  collectionInterval: [
    { required: true, message: '请设置数据采集间隔', trigger: 'blur' }
  ],
  timezone: [
    { required: true, message: '请选择系统时区', trigger: 'change' }
  ]
}

// 监控规则相关
const monitorRules = ref([])
const monitorRuleDialogVisible = ref(false)
const monitorRuleFormRef = ref(null)
const monitorRuleForm = reactive({
  id: '',
  name: '',
  type: 'resource',
  target: '',
  interval: 60,
  thresholds: [],
  status: 1
})

// 监控规则表单验证规则
const monitorRuleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择监控类型', trigger: 'change' }
  ],
  target: [
    { required: true, message: '请输入监控目标', trigger: 'blur' }
  ],
  interval: [
    { required: true, message: '请设置检查间隔', trigger: 'blur' }
  ]
}

// 告警规则相关
const alertRules = ref([])
const alertRuleDialogVisible = ref(false)
const alertRuleFormRef = ref(null)
const alertRuleForm = reactive({
  id: '',
  name: '',
  type: 'system',
  level: '中',
  channels: [],
  template: '',
  silencePeriod: 30,
  status: 1
})

// 告警规则表单验证规则
const alertRuleRules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择告警类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择告警级别', trigger: 'change' }
  ],
  channels: [
    { required: true, message: '请选择通知渠道', trigger: 'change' }
  ],
  template: [
    { required: true, message: '请输入通知模板', trigger: 'blur' }
  ]
}

// 初始化
onMounted(async () => {
  await loadSystemConfig()
  await loadMonitorRules()
  await loadAlertRules()
})

// 加载系统配置
const loadSystemConfig = async () => {
  try {
    const res = await getSystemConfig()
    Object.assign(systemConfig, res.data)
  } catch (error) {
    console.error('加载系统配置失败:', error)
    ElMessage.error('加载系统配置失败')
  }
}

// 保存系统配置
const handleSaveSystemConfig = async () => {
  if (!systemFormRef.value) return
  
  try {
    await systemFormRef.value.validate()
    await updateSystemConfig(systemConfig)
    ElMessage.success('系统配置保存成功')
  } catch (error) {
    console.error('保存系统配置失败:', error)
    ElMessage.error('保存系统配置失败')
  }
}

// 重置系统配置
const handleResetSystemConfig = () => {
  if (!systemFormRef.value) return
  systemFormRef.value.resetFields()
  loadSystemConfig()
}

// 加载监控规则列表
const loadMonitorRules = async () => {
  try {
    const res = await getMonitorRules()
    monitorRules.value = res.data
  } catch (error) {
    console.error('加载监控规则失败:', error)
    ElMessage.error('加载监控规则失败')
  }
}

// 添加监控规则
const handleAddMonitorRule = () => {
  Object.assign(monitorRuleForm, {
    id: '',
    name: '',
    type: 'resource',
    target: '',
    interval: 60,
    thresholds: [],
    status: 1
  })
  monitorRuleDialogVisible.value = true
}

// 编辑监控规则
const handleEditMonitorRule = (row) => {
  Object.assign(monitorRuleForm, row)
  monitorRuleDialogVisible.value = true
}

// 保存监控规则
const handleSaveMonitorRule = async () => {
  if (!monitorRuleFormRef.value) return
  
  try {
    await monitorRuleFormRef.value.validate()
    if (monitorRuleForm.id) {
      await updateMonitorRule(monitorRuleForm)
    } else {
      await createMonitorRule(monitorRuleForm)
    }
    ElMessage.success('监控规则保存成功')
    monitorRuleDialogVisible.value = false
    loadMonitorRules()
  } catch (error) {
    console.error('保存监控规则失败:', error)
    ElMessage.error('保存监控规则失败')
  }
}

// 删除监控规则
const handleDeleteMonitorRule = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该监控规则吗？', '提示', {
      type: 'warning'
    })
    await deleteMonitorRule(row.id)
    ElMessage.success('监控规则删除成功')
    loadMonitorRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除监控规则失败:', error)
      ElMessage.error('删除监控规则失败')
    }
  }
}

// 测试监控规则
const handleTestMonitorRule = async (row) => {
  try {
    const res = await testMonitorRule(row.id)
    ElMessage.success(`测试结果: ${res.data.result}`)
  } catch (error) {
    console.error('测试监控规则失败:', error)
    ElMessage.error('测试监控规则失败')
  }
}

// 监控规则状态变更
const handleMonitorRuleStatusChange = async (row) => {
  try {
    await updateMonitorRule({
      id: row.id,
      status: row.status
    })
    ElMessage.success('监控规则状态更新成功')
  } catch (error) {
    console.error('更新监控规则状态失败:', error)
    ElMessage.error('更新监控规则状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 添加阈值
const handleAddThreshold = () => {
  monitorRuleForm.thresholds.push({
    level: '中',
    operator: '>',
    value: 0
  })
}

// 删除阈值
const handleRemoveThreshold = (index) => {
  monitorRuleForm.thresholds.splice(index, 1)
}

// 加载告警规则列表
const loadAlertRules = async () => {
  try {
    const res = await getAlertRules()
    alertRules.value = res.data
  } catch (error) {
    console.error('加载告警规则失败:', error)
    ElMessage.error('加载告警规则失败')
  }
}

// 添加告警规则
const handleAddAlertRule = () => {
  Object.assign(alertRuleForm, {
    id: '',
    name: '',
    type: 'system',
    level: '中',
    channels: [],
    template: '',
    silencePeriod: 30,
    status: 1
  })
  alertRuleDialogVisible.value = true
}

// 编辑告警规则
const handleEditAlertRule = (row) => {
  Object.assign(alertRuleForm, row)
  alertRuleDialogVisible.value = true
}

// 保存告警规则
const handleSaveAlertRule = async () => {
  if (!alertRuleFormRef.value) return
  
  try {
    await alertRuleFormRef.value.validate()
    if (alertRuleForm.id) {
      await updateAlertRule(alertRuleForm)
    } else {
      await createAlertRule(alertRuleForm)
    }
    ElMessage.success('告警规则保存成功')
    alertRuleDialogVisible.value = false
    loadAlertRules()
  } catch (error) {
    console.error('保存告警规则失败:', error)
    ElMessage.error('保存告警规则失败')
  }
}

// 删除告警规则
const handleDeleteAlertRule = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该告警规则吗？', '提示', {
      type: 'warning'
    })
    await deleteAlertRule(row.id)
    ElMessage.success('告警规则删除成功')
    loadAlertRules()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除告警规则失败:', error)
      ElMessage.error('删除告警规则失败')
    }
  }
}

// 测试告警规则
const handleTestAlertRule = async (row) => {
  try {
    const res = await testAlertRule(row.id)
    ElMessage.success(`测试结果: ${res.data.result}`)
  } catch (error) {
    console.error('测试告警规则失败:', error)
    ElMessage.error('测试告警规则失败')
  }
}

// 告警规则状态变更
const handleAlertRuleStatusChange = async (row) => {
  try {
    await updateAlertRule({
      id: row.id,
      status: row.status
    })
    ElMessage.success('告警规则状态更新成功')
  } catch (error) {
    console.error('更新告警规则状态失败:', error)
    ElMessage.error('更新告警规则状态失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 工具方法
const getMonitorTypeTag = (type) => {
  const map = {
    resource: 'primary',
    performance: 'success',
    business: 'warning',
    security: 'danger'
  }
  return map[type] || 'info'
}

const getMonitorTypeLabel = (type) => {
  const map = {
    resource: '系统资源',
    performance: '性能指标',
    business: '业务指标',
    security: '安全指标'
  }
  return map[type] || type
}

const getAlertTypeTag = (type) => {
  const map = {
    system: 'danger',
    business: 'warning',
    performance: 'info',
    security: 'error'
  }
  return map[type] || 'info'
}

const getAlertTypeLabel = (type) => {
  const map = {
    system: '系统告警',
    business: '业务告警',
    performance: '性能告警',
    security: '安全告警'
  }
  return map[type] || type
}

const getAlertLevelTag = (level) => {
  const map = {
    严重: 'danger',
    高: 'error',
    中: 'warning',
    低: 'info'
  }
  return map[level] || 'info'
}

const getChannelLabel = (channel) => {
  const map = {
    email: '邮件',
    sms: '短信',
    webhook: 'Webhook',
    dingtalk: '钉钉',
    wechat: '企业微信'
  }
  return map[channel] || channel
}
</script>

<style lang="scss" scoped>
.monitor-config {
  padding: 20px;
  
  .config-form {
    max-width: 600px;
    margin: 0 auto;
  }
  
  .rule-header {
    margin-bottom: 20px;
  }
  
  .threshold-actions {
    margin-top: 10px;
    text-align: right;
  }
  
  .channel-tag {
    margin-right: 5px;
  }
  
  .unit {
    margin-left: 8px;
    color: #909399;
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 